package edu.je.column.service;

import edu.je.column.model.ArticleModel;
import edu.je.column.model.NewsModel;
import edu.je.column.repo.ArticleRepo;
import edu.je.column.repo.NewsRepo;
import edu.je.column.service.impl.NewsServcieImpl;
import edu.je.column.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author MengXin
 * @description:
 * @program: je-gateway
 * @date 2021/4/21 21:11
 * @mail mx@radish.cloud
 */
@Service
public class NewsService implements NewsServcieImpl{
    @Autowired
    NewsRepo newsRepo;

    @Autowired
    ArticleService articleService;

    @Override
    public NewsModel addNews(String title, String abstractContet, Long userId, String imageUrl,String content) {
        NewsModel addNews = new NewsModel();
        addNews.setTitle(title);
        addNews.setUserId(userId);
        addNews.setAbstractContent(abstractContet);
        addNews.setImageUrl(imageUrl);
        ArticleModel articleModel = articleService.addArticle(userId,title,1L,content);
        try {
            addNews.setArticleId(articleModel.getArticleId());
            System.out.println(addNews.getTitle());
            newsRepo.save(addNews);
            return addNews;
        }catch (Exception e){
            System.out.println(e);
            return null;
        }
    }

    @Override
    public List<NewsModel> getAllnews(Integer page,Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "postTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<NewsModel> models = newsRepo.findAll(pageable);
        return models.getContent();
    }
}
